package com.mo.demo.ehcache;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.VisibilityChecker;
import lombok.extern.slf4j.Slf4j;
import org.ehcache.impl.copy.ReadWriteCopier;


@Slf4j
public class EhcacheCopier<T> extends ReadWriteCopier<T> {

    public static final ObjectMapper jsonMapper = new ObjectMapper(){{
        disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        setVisibility(VisibilityChecker.Std.defaultInstance().withFieldVisibility(JsonAutoDetect.Visibility.ANY));
    }};

    public Class<EhcacheCopier<T>> getItsClass(){
        return (Class<EhcacheCopier<T>>)this.getClass();
    }


    @Override
    public T copy(T t) {
        try {
            byte[] bytes = jsonMapper.writeValueAsBytes(t);
            return jsonMapper.readValue(bytes, new TypeReference<T>(){});
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
